//
//  JYTregisteredViewController.m
//  JYT_IOS
//
//  Created by nxa-tankeke on 16/12/19.
//  Copyright © 2016年 nxa-yuanguoxiang. All rights reserved.
//

#import "JYTregisteredViewController.h"
#import "JYTProvince.h"
#import "JYTCity.h"
#import "JYTRegisteredHandler.h"

#define SECOND 60

@interface JYTregisteredViewController ()<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *frameView;
@property (weak, nonatomic) IBOutlet UIView *allView;

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UITextField *checkField;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;

@property (weak, nonatomic) IBOutlet UITextField *passwordField;

@property (weak, nonatomic) IBOutlet UITextField *cityField;
@property (weak, nonatomic) IBOutlet UIButton *cityBtn;

@property (weak, nonatomic) IBOutlet UIButton *registBtn;

@property(nonatomic, strong) UIPickerView *pickerView;
@property(nonatomic, copy) NSString *selectCityId;
@property(nonatomic, strong) NSArray *provinces;
@property(nonatomic, assign) NSInteger proIndex;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) int initialTimer;
@property(nonatomic, copy) NSString *userName;
@end

@implementation JYTregisteredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSDictionary *dic = @{@"lftBtnBgImg":@"ic_goback",
                          @"lftBtnTitle":@"no",
                          @"pageTitle":@"注册",
                          @"rhtBtnBgImg":@"no",
                          @"rhtBtnTitle":@"no"};
    
    [self setNavgationBarWithDic:dic];
    
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    _pickerView = pickerView;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    _selectCityId = nil;
    _provinces = [[JYTUserManager shared] getProviceArr];

    
    //self.frameView.layer.borderWidth = 1;
    //self.frameView.layer.borderColor = [[UIColor blueColor] CGColor];
    self.frameView.layer.cornerRadius = 4.0f;
    self.frameView.layer.masksToBounds = YES;
    
//    self.allView.layer.borderWidth = 1;
//    self.allView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.allView.layer.cornerRadius = 4.0f;
    self.allView.layer.masksToBounds = YES;
    
    UIColor *cDisabled = [UIColor colorWithRed:223/255.0f green:224/255.0f blue:225/255.0f alpha:1];
    [self.registBtn setBackgroundImage:[self createImageWithColor:cDisabled] forState:UIControlStateDisabled];
    //[self.commitBtn setBackgroundColor:];
    UIColor *cNormal = [UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1];
    [self.registBtn setBackgroundImage:[self createImageWithColor:cNormal] forState:UIControlStateNormal];
    
 
    
    self.passwordField.delegate = self;
    
    self.cityField.enabled = NO;
    self.cityField.inputView = _pickerView;
    self.cityField.delegate = self;
    
    self.registBtn.layer.cornerRadius = 4.0;
    self.registBtn.layer.masksToBounds = YES;
    self.registBtn.enabled = NO;
    [_textField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
    [_checkField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
    [_passwordField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
   
    [self.checkBtn.titleLabel setTextAlignment: NSTextAlignmentLeft];
    self.checkBtn.layer.cornerRadius = 4.0f;
    self.checkBtn.layer.masksToBounds = YES;
    self.cityBtn.layer.cornerRadius = 4.0f;
    self.cityBtn.layer.masksToBounds = YES;
    [self.checkBtn setBackgroundColor:[UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1]];
    [self.cityBtn setBackgroundColor:[UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1]];
    
}

- (void)textChange
{
    if (_textField.text.length && _checkField.text.length && _passwordField.text.length) {
        self.registBtn.enabled = YES;
    } else {
        self.registBtn.enabled = NO;
    }
 
   
}

-(void)viewWillDisappear:(BOOL)animated
{
    //销毁计时器
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (IBAction)clickCityBtn:(id)sender {
    
    self.cityField.enabled = YES;
    [self.cityField becomeFirstResponder];
}
 




- (IBAction)clickCheckBtn:(id)sender {
    
    NSString *phone =  self.textField.text;
    if (!phone || [phone isEqualToString:@" "] || [phone isEqualToString:@""])
    {
        [self showMessage:@"请输入手机号"];
        return;
    }
    _initialTimer = SECOND;
    
    if (phone.length >11 || phone.length < 11)
    {
        [self showMessage:@"手机号格式错误"];
        return;
        
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:phone];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:phone];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:phone];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            [[JYTRegisteredHandler shared] getCenterPinCodeWithPhone:phone withHandler:^(NSString *code, NSString *userName) {
                
                self.checkBtn.userInteractionEnabled = NO;
                [self.checkBtn setTitle:[NSString stringWithFormat:@"%02d秒后重新获取",SECOND] forState:0];
                _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerStart:) userInfo:nil repeats:YES];
                
                if ([code isEqualToString:@"1"]) {
                    
                    [self showMessage:@"短信验证码发送失败"];
                } else {
                    self.userName = userName;
                    MyLog(@"----------=======%@",self.userName);
                    [self showMessage:@"短信验证码发送成功"];
                }
                
            }];
            
        }else{
            [self showMessage:@"请输入正确的电话号码"];
            return;
        }
    }

    
}


- (IBAction)clickRegistBtn:(id)sender {
    
    NSString *phone = self.textField.text;
    
    NSString *pinCode = self.checkField.text;

    
    NSString *passWord =  self.passwordField.text;

    
    NSString *cityId = self.selectCityId;
    NSString *userName = self.userName;
    NSString *md5Pwd = [[JYTHttpClient sharedInstance] md5_base64:passWord];
    
    NSDictionary *par = @{@"UserName" : userName, @"Pwd" : md5Pwd ,@"CityId" : cityId, @"SecurityCode" : pinCode, @"Telphone" : phone};
    [[JYTRegisteredHandler shared] registerWithParams:par completionHandler:^(BOOL succ) {
        
        if (succ) {
            [self showMessage:@"注册成功"];
            [self goBack];
        } else {
            [self showMessage:@"验证码错误或验证码超时"];
        }
        
        
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    label.text = message;
    
    //    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    //初始化段落，设置段落风格
    
    NSMutableParagraphStyle *paragraphstyle=[[NSMutableParagraphStyle alloc]init];
    paragraphstyle.lineBreakMode=NSLineBreakByCharWrapping;
    
    //设置label的字体和段落风格
    
    NSDictionary *dic=@{NSFontAttributeName:label.font,NSParagraphStyleAttributeName:paragraphstyle.copy};
    
    //计算label的真正大小,其中宽度和高度是由段落字数的多少来确定的，返回实际label的大小
    
    CGRect rect=[label.text boundingRectWithSize:CGSizeMake(290, 9000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    CGSize LabelSize = CGSizeMake(rect.size.width, rect.size.height);
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((CURRENT_SCREEN_WIDTH - LabelSize.width - 20)/2, CURRENT_SCREEN_HEIGHT - 100, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:2 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

- (UIImage *)createImageWithColor:(UIColor *)color

{
    
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return theImage;
    
}

-(void)timerStart:(NSTimer *)theTimer {
    if (_initialTimer == 1){
        _initialTimer = 60;
        [self stop];
    }else{
        _initialTimer--;
        [self.checkBtn setTitle:[NSString stringWithFormat:@"%02d秒后重新获取",_initialTimer] forState:0];
        
    }
}
- (void)stop{
    self.checkBtn.userInteractionEnabled = YES;
    if (_timer) {
        [_timer invalidate]; //停止计时器
        [self.checkBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    //销毁计时器
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == _cityField) {
        return NO;
    } else
    {
        return YES;
    }
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        
        return self.provinces.count;
        
    }else{
        JYTProvince *p = self.provinces[_proIndex];
        
        return p.cities.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) { // 描述省会
        
        // 获取省会
        JYTProvince *p = self.provinces[row];
        return p.zone_name;
        
    }else{ // 描述选中的省会的城市
        // 获取选中的省会的角标
        NSInteger index = [pickerView selectedRowInComponent:0];
        
        // 获取选中省会
        JYTProvince *p = self.provinces[_proIndex];
        
        JYTCity *city = p.cities[row];
        NSString *cityName = city.zone_name;
        
        return cityName;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) { // 滚动省会,刷新城市（1列）
        
        // 记录当前选中的省会
        _proIndex = [pickerView selectedRowInComponent:0];
        
        [pickerView reloadComponent:1];
        
    }
    
    // 获取选中省会
    JYTProvince *p = self.provinces[_proIndex];
    
    // 获取选中的城市
    NSInteger cityIndex = [pickerView selectedRowInComponent:1];
    
    JYTCity *city = p.cities[cityIndex];
    NSString *cityName = city.zone_name;
    self.selectCityId = city.parent_id.stringValue;
    
    _cityField.text = [NSString stringWithFormat:@"%@%@",p.zone_name,cityName];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == _cityField) {
        [self pickerView:_pickerView didSelectRow:0 inComponent:0];
    }
    
}

@end
